import { useEffect, useState, useRef } from 'react';
import { Tag, message, Space } from 'antd';
import lodash from 'lodash'
import { getAlarmDataList, markAlarmDataAsReadByAlertId } from '@/pages/alarm/service'
import { history } from 'umi';
import NoticeIcon from './NoticeIcon';
import styles from './index.less';

const getNoticeData = (notices) => {
  if (!notices || notices.length === 0 || !Array.isArray(notices)) {
    return [];
  }

  const newNotices = notices.map((notice) => {
    const newNotice = { ...notice };

    // ID
    if (newNotice.id) {
      newNotice.key = newNotice.id;
    }

    // Title
    newNotice.title = `${notice.alert_item} (${notice.alert_category})`

    // Level
    newNotice.level = notice.alert_level;

    // Extra
    let label_elements = [];
    Object.keys(notice.labels).forEach((k) => {
      label_elements.push(
        <Tag key={k}>{k}={notice.labels[k]}</Tag>
      )
    })
    newNotice.extra = (
      <Space size={[0, 'small']} wrap>
        {
          label_elements
        }
      </Space>
    );
    return newNotice;
  });
  return newNotices
};

const NoticeIconView = () => {
  const [socket, setSocket] = useState(null);
  const [notices, setNotices] = useState([]);

  const initWebSocker = () => {
    // 1. 获取未读告警
    getAlarmDataList({
      deal_status: 0,
      pageSize: 1000,
    }).then((res) => {
      setNotices(res.data)
    }).catch((e) => {
      console.log(e)
    })

    // 2. 连接websocket
    const user_id = localStorage.getItem("userId")
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const con = new WebSocket(`${protocol}//${location.host}/ws/noticelcon/?user_id=${user_id}`);
    setSocket(con)
  }
  useEffect(() => {
    if (socket) { socket.colse }
    initWebSocker()
  }, []);
  if (socket) {
    socket.onmessage = (e) => {
      const result = JSON.parse(e.data)
      const newNotices = lodash.cloneDeep(notices)
      newNotices.push(result)
      setNotices(newNotices)
    }
  }
  const noticeData = getNoticeData(notices);
  const unreadMsg = noticeData.filter(item => !item.read)

  const changeReadState = (alert_id) => {
    markAlarmDataAsReadByAlertId([alert_id])
      .then(res => {
        setNotices(
          notices.map((item) => {
            const notice = { ...item };
            if (notice.alert_id === alert_id) {
              notice.read = true;
            }
            return notice;
          }),
        )
        return true
      })
      .catch((e) => {
        message.error(e)
        return false
      })
  };

  const clearReadState = (title, key) => {
    markAlarmDataAsReadByAlertId(notices.map(item => item.alert_id))
      .then(res => {
        setNotices(
          notices.map((item) => {
            const notice = { ...item };
            notice.read = true;
            return notice;
          }),
        )
        message.success(`${'清空了'} ${title}`);
        return true
      })
      .catch((e) => {
        message.error(e.message)
        return false
      })
  };

  return (
    <NoticeIcon
      className={styles.action}
      count={unreadMsg.length}
      onItemClick={(item) => {
        changeReadState(item.alert_id);
      }}
      onClear={(title, key) => clearReadState(title, key)}
      loading={false}
      clearText="清空"
      viewMoreText={<a onClick={() => {
        history.push("/alarm/list")
      }} >查看更多</a>}
      clearClose
    >
      {/* <NoticeIcon.Tab
        tabKey="notification"
        count={unreadMsg.notification}
        list={noticeData.notification}
        title="通知"
        emptyText="你已查看所有通知"
        showViewMore
      /> */}
      <NoticeIcon.Tab
        tabKey="warning"
        count={unreadMsg.length}
        list={noticeData}
        title="告警"
        emptyText="您已读完所有消息"
        showViewMore
      />
    </NoticeIcon>
  );
};

export default NoticeIconView;
